const express = require("express");
const router = express.Router();
const {success, successWithData} = require("../utils/result")
const { check } = require('express-validator');
const {checkParam}  = require("../utils/checkUtils")
const Address = require("../db/model/addressModel");

/**
 * 查询树形结构地址接口
 * @api {POST} /address/queryAddressList 查询树形结构地址接口
 * @apiDescription 查询树形结构分类接口
 * @apiName queryAddressList
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiParamExample {json} Request-Example:
 * {}
 * @apiGroup Address
 * @apiVersion 1.0.0
 */
 router.post("/address/queryAddressList", async function (req, res) {
  const { pcode } = req.body;
  let addressAll = []
  if(pcode || pcode == "0"){
    let resList = []
    addressAll = await Address.findAll({where: {pcode}});
    if(addressAll && addressAll.length > 0){
      resList = addressAll.map(item=>{
        if(item.dataValues.level == 3){
          item.dataValues["hasChildren"] = false
        }else{
          item.dataValues["hasChildren"] = true
        }
        return item;
      })
    }
    return res.json(successWithData(resList))
  }else{
    addressAll = await Address.findAll();
    if(addressAll && addressAll.length > 0){
      addressAll = toTreeData(addressAll,"0")
    }
    return res.json(successWithData(addressAll))
  }
});

function toTreeData(data,pcode){
  function tree(code) {
      let arr = []
      data.filter(item => {
          return item.pcode === code;
      }).forEach(item => {
          let children = tree(item.code)
          arr.push({
              ...item.dataValues,
              children: children,
              hasChildren: children && children.length > 0
          })
      })
      return arr
  }
  return tree(pcode)
}

/**
 * 分页查询接口
 * @api {POST} /address/queryAddressListByPage 分页查询接口
 * @apiDescription 分页查询接口
 * @apiName queryAddressListByPage
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "limit": "10",
 *     }
 * @apiGroup Address
 * @apiVersion 1.0.0
 */
router.post("/address/queryAddressListByPage", check('page').not().isEmpty(),check('limit').not().isEmpty(), async function (req, res) {
  checkParam(req)
  const { page, limit, type } = req.body;
  const where = {};
  let offset = (page - 1) * limit;
  if (type) {
    where["type"] = type;
  }
  const result = await Address.findAndCountAll({
    limit,
    offset,
    where,
    order: [["created_time", "DESC"]],
  });
  return res.json(successWithData(result));
});


/**
 * @api {POST} /address/add 添加
 * @apiDescription 添加
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键ID
 * @apiBody {String} code='地址编号'   地址编号
 * @apiBody {String} name='地址名称'   地址名称
 * @apiBody {String} pcode='父级地址编号'   父级地址编号
 * @apiBody {Number} level=1   地址级别
 * @apiBody {String} created_time='1994-04-01'   创建时间
 * @apiBody {String} updated_time='1994-04-01'   更新时间
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "code": '地址编号',
 *        "name": '地址名称',
 *        "pcode": '父级地址编号',
 *        "level": 1,
 *        "created_time": '1994-04-01',
 *        "updated_time": '1994-04-01',
 *     }
 * @apiGroup Address
 * @apiVersion 1.0.0
 */
router.post("/address/add",  async function (req, res) {
  await Address.create({...req.body});
  return res.json(success());
});


/**
 * @api {POST} /address/edit 编辑
 * @apiDescription 编辑
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键ID
 * @apiBody {String} code='地址编号'   地址编号
 * @apiBody {String} name='地址名称'   地址名称
 * @apiBody {String} pcode='父级地址编号'   父级地址编号
 * @apiBody {Number} level=1   地址级别
 * @apiBody {String} created_time='1994-04-01'   创建时间
 * @apiBody {String} updated_time='1994-04-01'   更新时间
 * @apiParamExample {json} Request-Example:
 *     {
 *        "code": '地址编号',
 *        "name": '地址名称',
 *        "pcode": '父级地址编号',
 *        "level": 1,
 *        "created_time": '1994-04-01',
 *        "updated_time": '1994-04-01',
 *     }
 * @apiGroup Address
 * @apiVersion 1.0.0
 */
router.post("/address/edit", check('id').not().isEmpty(),async function (req, res) {
  checkParam(req)
  await Address.update({...req.body}, {where: {id:req.body.id}});
  return res.json(success());
});

/**
 * @api {POST} /address/del 删除
 * @apiDescription 删除
 * @apiName del
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *     }
 * @apiGroup Address
 * @apiVersion 1.0.0
 */
router.post("/address/del", check('id').not().isEmpty(),async function (req, res) {
  checkParam(req)
  await Address.destroy({where: {id:req.body.id}});
  return res.json(success());
});
module.exports = router;